package com.smartshopping.iu;

import java.io.IOException;
import java.util.ArrayList;

import com.smartshopping.view.*;
import com.smartshopping.model.*;
import com.smartshopping.engine.*;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;

public class MarketActivity extends Activity {

	// Khai bao bien cuc bo
	private ArrayList<Market> array;
	private ListMarketAdapter arrayAdapter;
	private DataBaseHelper myDbHelper;
	private ArrayList<Coop> arrayCoop;
	private ArrayList<String> arrayStringCoop;
	private int curCoopID = 0;
	private SearchEngine search = new SearchEngine();
	
// <<------------------------------------------------------------------>>

	@Override
	// Khoi tao gia tri can ban su dung trong layout Market
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_market);	
		try {
			myDbHelper = new DataBaseHelper(this);
			myDbHelper.createDataBase(this);
			myDbHelper.openDataBase();
			createListCoop();
			createListMarket("","",curCoopID);
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}
		
		//Create the handler of change in search editText
		final EditText seachEditText = (EditText)findViewById(R.id.market_editText);
		seachEditText.addTextChangedListener(new TextWatcher(){
	        public void afterTextChanged(Editable s) {
	        	createListMarket(seachEditText.getText().toString(), "",curCoopID);	
	        }
	        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
	        public void onTextChanged(CharSequence s, int start, int before, int count){}
	    }); 
		
		//Create the search button
		ImageButton searchButton = (ImageButton) findViewById(R.id.market_imageButton_search);
		searchButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	createListMarket("", seachEditText.getText().toString(),curCoopID);	
	        }
	    });
		
		//Create market type button
		ImageButton typeButton = (ImageButton) findViewById(R.id.market_imageButton_coop);
		typeButton.setOnClickListener(new View.OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	showDialogButtonClick();
	        }
	    });
	}

// <<------------------------------------------------------------------>>
	
	// EFFECTS: Tao list of market trong market layout phu hop voi yeu cau nguoi su dung
	// REQUIRES:_Gia tri ban dau cua halfS va fullS la "", coopID = 0. Khi do se list ra toan bo danh sach 
	// 			sieu thi co trong database
	//			_Khi nguoi dung nhap vao khung search, gia tri cua halfS thay doi => xuat ra danh sach
	//			sieu thi phu hop voi halfS
	//			_Khi nguoi dung bam nut search, gia tri cua fullS thay doi => xuat ra danh sach
	//			phu hop voi fullS
	//			_coopID thay doi khi nguoi dung chon 1 group sieu thi xac dinh.
	//			Vi du: chon CoopMart => coopID = 1 => chi hien danh sach sieu thi cua CoopMart
	public void createListMarket(String halfS, String fullS, int coopID)
	{
		// Khai bao chuoi ky tu phu dung de tao cau lenh SQL
		String cond = "";
		if (coopID > 0)
			cond += " where coopID = " + Integer.toString(coopID);
		
		SQLiteDatabase mdb = myDbHelper.getReadableDatabase();
		String sql = "SELECT * FROM market" + cond + " order by name ASC";
		Cursor mCursor = mdb.rawQuery(sql, null);
		
		//Create the array for the List
				array = new ArrayList<Market>();
				if(mCursor.moveToFirst()){
					do {
						//Add vao ArrayList
						if (search.checkIsOktoPutOnList(halfS, fullS, mCursor.getString(1)))
							array.add(new Market(mCursor.getInt(0), mCursor.getString(1), mCursor.getString(2), mCursor.getInt(3), mCursor.getString(4), R.drawable.spmicon));
					} while (mCursor.moveToNext());
				}
				mCursor.close();
				mdb.close();
				arrayAdapter = new ListMarketAdapter(this, R.layout.activity_list_market_item, array);

				final ListView listView = ((ListView)findViewById(R.id.market_listview));
				listView.setAdapter(arrayAdapter);
				
				//Set the list listener for the list
				listView.setOnItemClickListener(new OnItemClickListener() 
					{
						@Override
						public void onItemClick(AdapterView<?> a, View v, int position, long id) 
						{
							Market market = (Market)listView.getItemAtPosition(position);
							Intent myIntent1 = new Intent(MarketActivity.this, ListGoodActivity.class);
							// Pass parameter to the next activity
							myIntent1.putExtra("coopID",Integer.toString(market.getCoopID()));
							myIntent1.putExtra("marketID",Integer.toString(market.getId()));
							MarketActivity.this.startActivity(myIntent1);
						}
					});
	}

// <<------------------------------------------------------------------>>
	
	//Create the list of type of good
	public void createListCoop() {
		//Open database
		SQLiteDatabase mdb = myDbHelper.getReadableDatabase();
		String sql = "select * from coop";
		Cursor mCursor = mdb.rawQuery(sql, null); 		
		System.out.println(mCursor.getCount());
		
		//Create the array for the List
		arrayCoop = new ArrayList<Coop>();
		arrayStringCoop = new ArrayList<String>();
		arrayStringCoop.add("Tất cả");
		if(mCursor.moveToFirst()){
			do {
				//Add vao ArrayList
				arrayStringCoop.add(mCursor.getString(1));
				arrayCoop.add(new Coop(mCursor.getInt(0), mCursor.getString(1)));
			} while (mCursor.moveToNext());
		}
		mCursor.close();
		mdb.close();
	}
	
// <<------------------------------------------------------------------>>
	
	//Create the dialog
	private void showDialogButtonClick() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Chọn loại sản phẩm");

		String[] choiceList = new String[arrayStringCoop.size()];
		choiceList = arrayStringCoop.toArray(choiceList);

		int selected = -1; // does not select anything
		
		builder.setSingleChoiceItems( choiceList, selected, new DialogInterface.OnClickListener() {         
		@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
				int position = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
				if (position > 0)
					curCoopID = arrayCoop.get(position - 1).getCoopId();
				else
					curCoopID = 0;
				createListMarket("", "",curCoopID);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
// <<------------------------------------------------------------------>>
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.index, menu);
		return true;
	}
}
